<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/

if (!defined ('EXPLAY')) exit;


class articlesMySQL {
	
	private $db;
	
	private static $instance = false;
	public static function getInstance () {
		if (self::$instance === false) self::$instance = new articlesMySQL;
			
		return self::$instance;
	}
	
	private function __construct () {
		$this->db = MySQL::getInstance();
	}
	
	//
	// Формируем запрос на выбор сиписка статей
	//
	public function db_select_list ($options_str, $order, $start, $number) {
		$query_string = "SELECT SQL_CACHE
				art_id,
				art_header,
				art_category,
				art_body,
				art_publik,
				art_author,
				art_date,
				art_image,
				art_tags,
				art_community,
				art_rating,
				art_voters,
				auto_tag,
				art_visible,
				category.cat_header,
				users.user_name,
				users.user_login,
				comments.cnt_com,
				category.cat_header,
				category.cat_description,
				category.cat_voters,
				category.cat_rating,
				category.cat_id
			FROM ".DB_PEREFIX."_articles AS articles
			
				LEFT JOIN (
					SELECT
						cat_id,
						cat_name,
						cat_header,
						cat_description,
						cat_rating,
						cat_voters
					FROM ".DB_PEREFIX."_art_category
					
				) AS category ON articles.art_category = category.cat_name
					
				LEFT JOIN (
					SELECT
						user_id,
						user_name,
						user_login
					FROM ".DB_PEREFIX."_users
				) AS users ON articles.art_author = users.user_id
				
				LEFT JOIN (
					SELECT
						COUNT(*) AS cnt_com,
						com_category,
						com_idi
					FROM ".DB_PEREFIX."_comments WHERE com_category = 'articles' GROUP BY com_idi
				) AS comments ON comments.com_idi = articles.art_id
			
			WHERE ".$options_str." ORDER BY ".$order." DESC LIMIT ".$start.", ".$number;
		
		//print $query_string;
		//exit;
		
		return $this->db->query ($query_string);
	}
	
	//
	// Запрос на выборку одной статьи для ее отображения
	//
	public function db_select_article ($options_str) {
	
		$query_string = "SELECT SQL_CACHE
			art_id,
			art_header,
			art_category,
			art_body,
			art_author,
			art_date,
			art_comments,
			art_image,
			art_tags,
			art_rating,
			art_voters,
			art_like_page,
			auto_tag,
			art_visible,
			users.user_name,
			users.user_login,
			category.cat_header,
			category.cat_description,
			category.cat_voters,
			category.cat_rating,
			category.cat_id
		FROM ".DB_PEREFIX."_articles AS articles
			
			LEFT JOIN (
				SELECT
					user_id,
					user_name,
					user_login
				FROM ".DB_PEREFIX."_users) AS users ON articles.art_author = users.user_id
			
			LEFT JOIN (
				SELECT
					cat_id,
					cat_name,
					cat_header,
					cat_description,
					cat_voters,
					cat_rating
				FROM ".DB_PEREFIX."_art_category) AS category ON articles.art_category = category.cat_name
		
		WHERE ".$options_str;
		
		return $this->db->query ($query_string);
	}
	
	public function add_article ($art) {
		$this->db->query ("INSERT INTO ".DB_PEREFIX."_articles VALUES (
						0,
						'".$art['art_category']."',
						'".$art['art_header']."',
						'".$art['art_body']."',
						'".User::$properties['user_id']."',
						'".time()."',
						'".$art['art_comments']."',
						'',
						'',
						'".$art['art_publik']."',
						'no',
						'".$art['art_visible']."',
						'".$art['art_tags']."',
						'0',
						'',
						'0',
						'".$art['auto_tag']."'
		)");
	}
	
	//
	// Считаем кол-во статей
	//
	public function get_count ($options_str) {
		$count = $this->db->fetch_array ($this->db->query ("SELECT COUNT(*) AS cnt FROM ".DB_PEREFIX."_articles WHERE ".$options_str));
		
		return $count['cnt'];
	}
	
	//
	// Проверяем подключен ли пользователь к блогу
	//
	public function in_blog ($id, $uid) {
		return $this->db->num_rows ($this->db->query ("SELECT * FROM ".DB_PEREFIX."_blogs_users WHERE blog = ".$id." AND user = ".$uid));
	}
	
	//
	// Подсчет кол-ва пользователей в блоге
	//
	public function count_users_in_blog ($id) {
		$get = $this->db->fetch_array ($this->db->query ("SELECT COUNT(*) AS cnt FROM ".DB_PEREFIX."_blogs_users WHERE blog = ".$id));
		return ($get['cnt'] == '') ? 0 : $get['cnt'];
	}
	
	//
	// Берем теги
	//
	public function get_tags () {
		return $this->db->query ("SELECT art_tags FROM ".DB_PEREFIX."_articles ORDER BY art_id DESC LIMIT 0, 400");
	}
	
	/**
	 * Сохранение статьи
	 */
	public function save_article ($fields, $id) {
		$write_arr = array ();
		
		foreach ($fields as $field) {
			$field = current ($fields);
			array_push ($write_arr, ' '.key ($fields)." = '".$field."' ");
			next ($fields);
		}
		
		$write = implode (', ', $write_arr);
		unset ($write_arr);

		$this->db->query ("UPDATE ".DB_PEREFIX."_articles SET $write WHERE art_id = $id");
	}
	
	/**
	 * Удаление статьи
	 */
	public function delete_article ($options_str) {
		$this->db->query ("DELETE FROM ".DB_PEREFIX."_articles WHERE $options_str");
		return;
	}
	
	/**
	 * Сохранение блога
	 */
	public function save_blog ($header, $description, $id) {
		$this->db->query ("UPDATE ".DB_PEREFIX."_art_category SET cat_header = '$header', cat_description = '$description' WHERE cat_id = $id");
		return;
	}
	
	/**
	 * Добавление нового блога
	 */
	public function add_blog ($blog) {
		$this->db->query ("INSERT INTO ".DB_PEREFIX."_art_category VALUES (0, '".$blog['cat_name']."', '".$blog['cat_header']."', '".$blog['cat_description']."', '0', '', '".time()."', 'yes', '".User::$properties['user_id']."')");
		$this->db->query ("INSERT INTO ".DB_PEREFIX."_blogs_users VALUES (".User::$properties['user_id'].", ".mysql_insert_id ().")");
		return;
	}
	
	/**
	 * Возвращает блог
	 */
	public function select_blog ($options_str) {
		return $this->db->query ("SELECT * FROM ".DB_PEREFIX."_art_category WHERE $options_str");
	}
	
	/**
	 * Возвращает блоги пользователя
	 */
	public function select_user_blogs ($uid) {
		return $this->db->query ("SELECT * FROM ".DB_PEREFIX."_art_category WHERE cat_author = $uid");
	}
	
	/**
	 * Возвращает все доступные пользователям на запись блоги
	 */
	public function get_all_writable_blogs () {
		return $this->db->query ("SELECT cat_name, cat_header FROM ".DB_PEREFIX."_art_category WHERE allow_users = 'yes' ORDER BY cat_header");
	}
	
	/**
	 * Возвращает блоги, к которым подключен пользоватеь
	 */
	public function get_user_included_blogs () {
		return $this->db->query ("SELECT  b.cat_name, b.cat_header FROM ".DB_PEREFIX."_blogs_users AS u
				LEFT JOIN (SELECT cat_id, cat_name, cat_header FROM ".DB_PEREFIX."_art_category) AS b ON b.cat_id = u.blog
				WHERE user = ".User::$properties['user_id']);
	}
		
}